import routes, { RouteObject } from '../config/routes';
import { isEmptyArray } from './utils';

const filterRoutesByPermission = function (
  routes: RouteObject[],
  permins: string[],
) {
  const originData = [...routes] as RouteObject[];
  const result: string[] = [];

  const filter = function (childrenArr: RouteObject[]) {
    if (!childrenArr?.length) return false;
    for (let item of childrenArr) {
      if (permins.includes(item?.accessKey as string)) {
        result.push(item?.accessKey as string);
        return true;
      }
      if (filter(item?.routes as RouteObject[])) {
        result.push(item?.accessKey as string);
        return true;
      }
    }
    return false;
  };

  originData.forEach((item: any) => {
    if (isEmptyArray(item?.routes)) {
      if (permins.includes(item?.accessKey)) {
        result.push(item?.accessKey);
      }
    } else {
      if (filter(item?.routes)) {
        result.push(item?.accessKey);
      }
    }
  });

  return result;
};
export const getInitialState = async (value: any) => {
  const getuserInfo = async () => {
    return await new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          name: '张三',
          avatar:
            'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
          email: 'zhangsan@example.com',
          phone: '12345678901',
          role: 'admin',
        });
      }, 1000);
    });
  };
  const userInfo = await getuserInfo();

  const getPermission = async () => {
    return await new Promise((resolve) => {
      const permins: string[] = [
        'access-test-detail',
        'access-test',
        'form-test',
        'back-table',
        'back-protable',
        'access-deep-level1-comp1',
        'print-test'
      ];

      const filterResult = filterRoutesByPermission(routes, permins);
      console.log(filterResult, 'filterResult');
      setTimeout(() => {
        resolve({
          currentPermission: filterResult,
          originPerminssions: permins,
        });
      }, 1000);
    });
  };
  const { originPerminssions, currentPermission }: any = await getPermission();

  return { userInfo, originPerminssions, currentPermission };
};
